﻿using System;
using Dapper;
using System.Data;
using System.Text.Json;
using System.Text.Encodings.Web;

namespace EaseDapper
{
    public class JsonObjectTypeHandler : SqlMapper.ITypeHandler
    {
        public void SetValue(IDbDataParameter parameter, object value)
        {
            parameter.Value = (value == null)
                ? (object)DBNull.Value
                : JsonSerializer.Serialize(value, new JsonSerializerOptions
                {
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });
            parameter.DbType = DbType.String;
        }

        public object Parse(Type destinationType, object value)
        {
            return JsonSerializer.Deserialize(value.ToString(), destinationType);
        }
    }
}
